package com.qire.antsrouter.lifecycleHandler;

import android.app.Activity;
import android.os.Bundle;

import com.qire.antsrouter.card.CardBag;
import com.qire.antsrouter.card.FloorCard;
import com.qire.antsrouter.card.Postcard;

import java.util.Stack;

/**
 * Activity管理处理程序,维护Activity栈
 */
public class ActivityManageHandler extends ActivityLifecycleHandler {

    public static final ActivityManageHandler HANDLER = new ActivityManageHandler();

    /**
     * activity栈
     */
    private final Stack<Activity> activityStack = new Stack<>();

    private ActivityManageHandler() {}

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        super.onActivityCreated(activity, savedInstanceState);
        addActivity(activity);

        int cardId = activity.getIntent().getIntExtra(Postcard.CARD_KEY, -1);
        FloorCard floorCard = CardBag.takeCard(cardId);
        if(floorCard != null) {
            floorCard.inject(activity);
        }
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        super.onActivityDestroyed(activity);
        removeActivity(activity);
    }

    /**
     * 添加Activity到堆栈
     */
    private void addActivity(Activity activity) {
        if(activity == null) {
            return;
        }
        if(!activityStack.contains(activity)) {
            activityStack.add(activity);
        }
    }
    /**
     * 移除Activity到堆栈
     */
    private void removeActivity(Activity activity) {
        activityStack.remove(activity);
    }

    /**
     * 栈内只有最后一个Activity了
     * @return true 表示栈内以到底了， false 表示还有多个
     */
    public boolean isLastOne() {
        return activityStack.size() <= 1;
    }

    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    public Activity currentActivity() {
        if (!activityStack.isEmpty()) {
            return activityStack.lastElement();
        } else {
            return null;
        }
    }
    /**
     * 获取上一个 Activity（堆栈中倒数第二个压入的）
     * 如果栈是空的，则返回null，如果栈只有一个activity，返回当前的这一个，否则，返回上一个
     */
    public Activity previousActivity() {
        if (!activityStack.isEmpty()) {
            int previousIndex = Math.max(0, activityStack.size() - 2);
            return activityStack.get(previousIndex);
        } else {
            return null;
        }
    }

    /**
     * 正序获取Activity通过指定类类型
     */
    public <T extends Activity> T findActivityBy(Class<T> cls) {
        for (Activity activity : activityStack) {
            if (cls.isInstance(activity)) {
                return (T) activity;
            }
        }
        return null;
    }

    /**
     * 倒序获取Activity通过指定类类型
     */
    public <T extends Activity> T findLastActivityBy(Class<T> cls) {
        int stackSize = activityStack.size();
        for(int index = stackSize - 1; index >= 0; index--) {
            Activity activity = activityStack.get(index);
            if(cls.isInstance(activity)) {
                return (T) activity;
            }
        }
        return null;
    }

    /**
     * 退出到目标Activity
     * @param dstActivity 目标Activity
     */
    public void finishTo(Activity dstActivity) {
        if(dstActivity == null || activityStack.isEmpty()) {
            return;
        }
        int lastIndex = activityStack.size() - 1;
        for(int i = lastIndex; i >= 0; i--) {
            Activity activity = activityStack.get(i);
            if(dstActivity.equals(activity)) {
                return;
            }
            activity.finish();
        }
    }

    /**
     * 结束所有Activity
     */
    public void finishAll() {

//        Iterator<Activity> it = activityStack.iterator();
//        Activity ac=null;
//        while(it.hasNext()){
//            ac = it.next();
//            it.remove();
//            ac.finish();
//        }

        for (int i = 0; i < activityStack.size(); i++) {
            if (null != activityStack.get(i)) {
                activityStack.get(i).finish();
            }
        }
        activityStack.clear();
    }

    /**
     * 退出app
     */
    public void exit() {
        try {
            finishAll();
//            DaoManager.getInstance().closeDataBase();
//            //如果开发者调用Process.kill或者System.exit之类的方法杀死进程
//            //请务必在此之前调用MobclickAgent.onKillProcess(Context context)方法，用来保存统计数据。
//            MobclickAgent.onKillProcess(AppUtils.getContext());
//            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

} 
